<template>
	<div class="add-profile">
		<div style="margin-bottom: 20px;">
			<el-button type="primary" size="medium" plain @click="back">
				返回
			</el-button>
		</div>
		<H3>档案详情</H3>
		<div class="form-data">
			<el-form :model="profileForm" inline :rules="rules" ref="ruleForm" 
				label-position="top">
				<el-form-item label="职工姓名" prop="userId">
					<el-input type="text" :value="profileForm.employeeName"
						placeholder="选择职工" readonly @focus="userShow" :disabled="isEditShow">
					</el-input>
				</el-form-item>
				<el-form-item label="职工状态">
					<el-select v-model="profileForm.employeeStatus" placeholder="状态" disabled
						style="width: 100%;">
						<el-option label="离职" :value="0"></el-option>
						<el-option label="在职" :value="1"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="性别" prop="employeeSex">
					<el-select v-model="profileForm.employeeSex" placeholder="选择性别"
						style="width: 100%;">
						<el-option label="男" :value="0"></el-option>
						<el-option label="女" :value="1"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="年龄" prop="employeeAge">
					<el-input type="number" v-model="profileForm.employeeAge"
						placeholder="输入年龄" >
					</el-input>
				</el-form-item>
				<el-form-item label="手机号码" prop="employeeEmail">
					<el-input type="text" v-model="profileForm.employeeEmail"
						placeholder="输入手机号码">
					</el-input>
				</el-form-item>
				<el-form-item label="身份证号" prop="employeeIdcard">
					<el-input type="text" v-model="profileForm.employeeIdcard"
						placeholder="输入身份证号">
					</el-input>
				</el-form-item>
				<el-form-item label="出生日期" prop="employeeBirthday">
					<el-date-picker v-model="profileForm.employeeBirthday" type="date"
						placeholder="选择出生日期" style="width: 100%;">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="入职日期" prop="employeeEntryDate">
					<el-date-picker v-model="profileForm.employeeEntryDate" type="date"
						placeholder="选择入职日期" style="width: 100%;">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="离职日期" prop="employeeLeaveDate">
					<el-date-picker v-model="profileForm.employeeLeaveDate" type="date"
						placeholder="选择离职日期" style="width: 100%;">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="合同到期日期" prop="employeeContractDate">
					<el-date-picker v-model="profileForm.employeeContractDate" type="date"
						placeholder="选择合同到期日期" style="width: 100%;">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="备注" prop="employeeRemark">
					<el-input type="textarea" :rows="4" placeholder="请输入内容" 
						v-model="profileForm.employeeRemark">
					</el-input>
				</el-form-item>
				<el-form-item label="合同图片">
					<div style="display: flex;">
						<div class="order-img-div" v-for="(item,index) in contractUrlList" 
							:key="index" style="position: relative;margin-right: 10px;">
							<el-image :src="item" class="htimg"
								:preview-src-list="contractUrlList">
							</el-image>
							<i class="el-icon-close hover-icon" @click="deleteImg(1,index)"></i>
						</div>
						<img :src="imgUrl" class="htimg" @click="selectFile(1)"
							v-if="contractUrlList.length < 3"/>
					</div>
				</el-form-item>
				<el-form-item label="保密协议图片">
					<div style="display: flex;">
						<div class="order-img-div" v-for="(item,index) in secrecyUrlList" 
							:key="index" style="position: relative;margin-right: 10px;">
							<el-image :src="item" class="htimg"
								:preview-src-list="secrecyUrlList">
							</el-image>
							<i class="el-icon-close hover-icon" @click="deleteImg(1,index)"></i>
						</div>
						<img :src="imgUrl" class="htimg" @click="selectFile(2)"
							v-if="secrecyUrlList.length < 3"/>
					</div>
				</el-form-item>
			</el-form>
			<div>
				<el-button @click="reset">重置</el-button>
				<el-button @click="onSubmit" type="primary" v-debounce>
					{{root ? '提交' : '申请修改'}}
				</el-button>
			</div>
		</div>
		<!-- 选择用户弹窗 -->
		<el-dialog style="margin-top:0" :visible.sync="userDialogShow" width="70%" title="选择职工" 
			@close="closeDialog">
			<div style=" width: 100%;display: flex;justify-content: flex-end;">
				<!-- 条件查询 -->
				<div>
					<el-input v-model="userForm.nickName" placeholder="按手机号或姓名搜索" clearable
						@change="submitUser" @clear="resetUser" style="width: 180px;">
					</el-input>
					<el-select v-model="userForm.roleId" placeholder="角色类型" value-key="id"
						style="width: 120px;" @change="submitUser" clearable>
						<el-option v-for="item in roleOptions" :key="item.id" :label="item.nameZh"
							:value="item.id" :disabled="item.enabled != 1">
						</el-option>
					</el-select>
				</div>
			</div>
			<div class="department-table">
				<el-table :data="userList" v-loading="userLoading" border stripe max-height="300">
					<el-table-column prop="i" label="序号" width="60"></el-table-column>
					<el-table-column prop="nickName" label="姓名" fit></el-table-column>
					<el-table-column prop="roleName" label="角色" fit ></el-table-column>
					<el-table-column label="操作" width="100" fixed="right">
						<template slot-scope="scope">
							<el-button type="text" @click="selectUser(scope.row)" 
								:disabled="profileIdList.indexOf(scope.row.id) > -1">
								选择
							</el-button>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination background :current-page="userForm.currentPage" 
					:page-size="userForm.pageSize" :page-sizes="[20, 50, 100]"
					@size-change="userSizeChange" @current-change="userCurrentChange"
					layout="total, sizes, prev, pager, next, jumper" :total="userForm.total">
				</el-pagination>
			</div>
		</el-dialog>
		<input type="file" id="fileInput" ref="fileInput" style="display: none" @change="handleFileChange" />
	</div>
</template>

<script>
	import profileApi from "../../api/employeeProfile.js";
	import userApi from "../../api/user.js";
	import roleApi from "../../api/role.js";
	import config from "../../api/apiURL.js";
	import uploadFile from '../../api/uploadFile.js';
	export default {
		data() {
			return {
				isEditShow: false,
				userInfo: {},
				root: false,
				profileForm: {
					id: null,
					userId: null, // 用户id
					employeeName: null, // 用户名
					employeeSex: 0, // 性别
					employeeEmail: null, // 电话号码
					employeeBirthday: null, // 生日
					employeeAge: null, // 年龄
					employeeIdcard: null, // 身份证号
					employeeEntryDate: null, // 入职日期
					employeeLeaveDate: null, // 离职日期
					employeeContractDate: null, // 合同到期日期
					employeeRemark: null, // 职工备注
					employeeContractFile: null, // 合同图片
					employeeSecrecyFile: null, // 保密协议图片
					employeeStatus: null, // 职工状态（0在职，1离职）
					employeeUpdateStatus: null, // 修改状态（0待审核，1已通过，2未通过）
					employeeUpdateCount: null, // 修改次数
				},
				rules: {
					employeeSex: [{
						required: true,
						message: '请选择性别',
						trigger: 'blur'
					}],
					employeeEmail: [{
						required: true,
						message: '请输入手机号码',
						trigger: 'blur'
					}, {
						pattern: /^[1][3-9][0-9]{9}$/,
						message: '请输入正确的手机号码',
						trigger: 'blur'
					}],
					employeeBirthday: [{
						required: true,
						message: '请选择出生日期',
						trigger: 'change'
					}],
					employeeAge: [{
						required: true,
						message: '请输入年龄',
						trigger: 'blur'
					}],
					employeeIdcard: [{
						required: true,
						message: '请输入身份证号',
						trigger: 'blur'
					},{
						pattern: /(^\d{17}[\dXx]$)/,
						message: '请输入正确的身份证号码格式',
						trigger: 'blur'
					}],
					employeeEntryDate: [{
						required: true,
						message: '请选择入职日期',
						trigger: 'change'
					}],
					// employeeLeaveDate: [{
					// 	required: true,
					// 	message: '请选择离职日期',
					// 	trigger: 'change'
					// }],
					employeeContractDate: [{
						required: true,
						message: '请选择合同到期日期',
						trigger: 'change'
					}],
				},
				selectedFile: "",
				imgUrl: "",
				imgType: 0, // 1合同图片，2保密协议
				contractUrl: [],
				contractUrlList: [],
				secrecyUrl: [],
				secrecyUrlList: [],
				userDialogShow: false,
				userLoading: false,
				userList: [],
				userForm: {
					nickName: null,
					roleId: null,
					currentPage: 1,
					pageSize: 50,
					total: 0,
				},
				roleOptions: [],
				profileIdList: [],
				
			}
		},
		created() {
			this.userInfo = JSON.parse(localStorage.getItem("userInfo"))
			if (this.userInfo.roleId == 1){
				this.root = true
			}
			let profileId = localStorage.getItem("profileId")
			if (profileId) {
				this.isEditShow = true;
				this.profileForm.id = profileId;
				this.getEmployeeProfile();
			};
			this.imgUrl="https://kris-k.oss-cn-hangzhou.aliyuncs.com/kris/c179093a-41b0-4c70-bc1f-6e5973f35c98-jia.png"
		},
		destroyed() {
			localStorage.removeItem("profileId");
		},
		methods: {
			// 返回
			back() {
				this.$router.push({
					path: "/goods/goods"
				})
			},
			// 获取已有档案的用户ID
			getProfileIdList(){
				return new Promise(resolve =>{
					profileApi.getProfileIdList().then(res =>{
						if (res.code === 200){
							this.profileIdList = res.data;
							resolve(res.data);
						}
					})
				})
			},
			// 获取个人档案
			getEmployeeProfile() {
				const loading = this.$loading({
					lock: true,
					text: 'Loading...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				profileApi.getEmployeeProfile(this.profileForm).then(res => {
					if (res.code == 200) {
						this.profileForm = res.data;
						this.contractUrl = res.data.contractUrl;
						if (this.contractUrl != null){
							this.contractUrl.forEach(item =>{
								this.contractUrlList.push(config.READ_IMG_URL+item);
							})
						}else {
							this.contractUrl = []
						}
						this.secrecyUrl = res.data.secrecyUrl;
						if (this.secrecyUrl != null){
							this.secrecyUrl.forEach(item =>{
								this.secrecyUrlList.push(config.READ_IMG_URL+item);
							})
						}else {
							this.secrecyUrl = []
						}
					}
				}).finally(() => {
					loading.close();
				})
			},
			// 显示选择用户弹窗
			userShow() {
				this.userDialogShow = true;
				this.getProfileIdList().then(data =>{
					this.getUserList();
					this.getRoleList();
				})
			},
			// 关闭弹窗
			closeDialog(){
				this.userForm.nickName = null;
				this.userForm.currentPage = 1;
				this.userDialogShow = false;
			},
			// 提交
			onSubmit(){
				let _this = this;
				this.$refs.ruleForm.validate((valid) => {
					if (!valid) {
						_this.$message.error("请将表单填写完整!")
						return false;
					}
					if(this.profileForm.userId == null || this.profileForm.userId === ''){
						_this.$message.error("请选择员工!")
						return false;
					}
					const loading = this.$loading({
						lock: true,
						text: 'Loading...',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					});
					if (this.isEditShow){
						// 修改
						profileApi.updateEmployeeProfile(this.profileForm).then(res =>{
							if (res.code == 200){
								this.$message.success("提交成功");
								this.back();
							}
						}).finally(() =>{
							loading.close();
						})
					}else {
						// 添加
						profileApi.addEmployeeProfile(this.profileForm).then(res =>{
							if (res.code == 200){
								this.$message.success("提交成功");
								this.back();
							}
						}).finally(() =>{
							loading.close();
						})
					}
				});
			},
			// 重置
			reset(){
				this.$refs.ruleForm.resetFields();
			},
			//获取所有角色列表
			getRoleList() {
				roleApi.getRoleList().then(res =>{
					if (res.code === 200){
						this.roleOptions = res.data;
					}
				})
			},
			// 获取用户
			getUserList() {
				this.userLoading = true
				userApi.fuzzyQuery(this.userForm).then(res => {
					if (res.code === 200) {
						this.userList = res.data.userVoList.map((item,index) =>{
							item.i = (this.userForm.currentPage - 1)*this.userForm.pageSize+index+1;
							return item;
						})
						this.userForm.total = res.data.total;
					}
				}).finally(() =>{
					this.userLoading = false
				})
			},
			submitUser(){
				this.userForm.currentPage = 1;
				this.getUserList();
			},
			resetUser(){
				this.userForm.nickName = null;
				this.submitUser();
			},
			userCurrentChange(curPage){
				this.userForm.curPage = curPage;
				this.getUserList();
			},
			userSizeChange(pageSize){
				this.userForm.pageSize = pageSize;
				this.getUserList();
			},
			// 选择用户
			selectUser(item){
				// console.log("item===>",item)
				this.profileForm.userId = item.id
				this.profileForm.employeeName = item.nickName
				this.profileForm.employeeStatus = item.state
				this.profileForm.employeeSex = item.sex
				this.profileForm.employeeEmail = item.phone
				this.closeDialog();
			},
			// 点击上传图片
			selectFile(type) {
				this.imgType = type;
				this.$refs.fileInput.click();
			},
			// 选择文件
			handleFileChange(event) {
				this.selectedFile = event.target.files[0];
				// 上传前验证
				const fileSuffix = this.selectedFile.name.substring(this.selectedFile.name.lastIndexOf(".") + 1);
				const whiteList = ["jpg", "jpeg", "png", "JPG", "JPEG", "PNG"];
				if (whiteList.indexOf(fileSuffix) === -1) {
					this.$message.error("上传文件只能是 jpg、png格式！");
					return;
				}
				const isLt5M = this.selectedFile.size / 1024 / 1024 < 5;
				if (!isLt5M) {
					this.$message.error('上传的图片大小不能超过5MB!');
					return;
				}
				this.uploadImage();
			},
			//发送上传文件api
			uploadImage() {
				const loading = this.$loading({
					lock: true,
					text: '上传中...',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				let formData = new FormData();
				formData.append("file", this.selectedFile);
				uploadFile.uploadImage(formData).then(res =>{
					if (res.code === 200){
						const url = res.data
						if (this.imgType === 1) {
							this.contractUrl.push(url);
							this.contractUrlList.push(config.READ_IMG_URL+url);
							this.profileForm.employeeContractFile = this.contractUrl.join(";");
							this.$message.success("上传成功");
						} else if (this.imgType === 2) {
							this.secrecyUrl.push(url);
							this.secrecyUrlList.push(config.READ_IMG_URL+url);
							this.profileForm.employeeSecrecyFile = this.secrecyUrl.join(";");
							this.$message.success("上传成功");
						}
					}
				}).finally(() =>{
					this.selectedFile = '';
					loading.close();
				})
			},
			// 删除图片
			deleteImg(type,index){
				if (this.isEditShow){
					this.$confirm('是否要删除此图片？', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						// 用户点击了确定按钮时执行的操作
						this.doDeleteImg(type,index);
					}).catch(() => {
						// 用户点击了取消按钮时执行的操作，或者点击遮罩层关闭对话框时触发的事件
						
					});
				}else {
					this.doDeleteImg(type,index);
				}
			},
			doDeleteImg(type,index){
				if (type === 1){
					this.contractUrl.splice(index,1);
					if (this.contractUrl.length > 0){
						this.profileForm.employeeContractFile = this.contractUrl.join(";");
					}else {
						this.profileForm.employeeContractFile = ''
					}
					this.contractUrlList = [];
					this.contractUrl.forEach(item =>{
						this.contractUrlList.push(config.READ_IMG_URL+item);
					})
					this.$message.success("删除成功");
				}else if (type === 2){
					this.secrecyUrl.splice(index,1);
					if (this.secrecyUrl.length >0){
						this.profileForm.employeeSecrecyFile = this.secrecyUrl.join(";")
					}else {
						this.profileForm.employeeSecrecyFile = ''
					}
					this.secrecyUrlList = [];
					this.secrecyUrl.forEach(item =>{
						this.secrecyUrlList.push(config.READ_IMG_URL+item);
					})
					this.$message.success("删除成功");
				}
			},
		}
	}
</script>

<style scoped>
	
	.el-form-item{
		width: 450px;
		margin-right: 20px;
	}
	
	.htimg {
		width: 150px;
		height: 150px;
		object-fit: cover;
		/* 保持原始宽高比，填充容器 */
	}
	
	.order-img-div{
		width: 150px;
		height: 150px;
	}
	
	.order-img-div:hover .hover-icon{
		display: block;
	}
	
	.hover-icon{
		display: none;
		font-size: 24px;
		position: absolute;
		top: 0; 
		right: 0;
		color: #ffffff;
		background-color: black;
		opacity: 0.9
	}
	
	.hover-icon:hover{
		cursor: pointer;
	}
</style>